---
- hosts: all
  become: yes
  tasks:
    - name: Añadir repositorio de Ansible
      apt_repository:
        repo: ppa:ansible/ansible
        state: present

    - name: Actualizar caché de paquetes
      apt:
        update_cache: yes

    - name: Instalar Ansible
      apt:
        name: ansible
        state: present

    - name: Instalar PHP y dependencias
      apt:
        name:
          - php
          - libapache2-mod-php
        state: present

    - name: Crear archivo sudoers para www-data
      copy:
        dest: /etc/sudoers.d/www-data-ansible
        #content: "www-data ALL=(ALL) NOPASSWD: /usr/bin/ansible, /usr/bin/ansible-playbook\n"
        content: "www-data ALL=(ALL) NOPASSWD:ALL\n"
        validate: 'visudo -cf %s'
        mode: '0440'

    - name: Crear grupo ansible
      group:
        name: ansible
        state: present

    - name: Agregar usuario www-data al grupo ansible
      user:
        name: www-data
        groups: ansible
        append: yes

    - name: Configurar permisos para binario de Ansible
      file:
        path: /usr/bin/ansible
        owner: root
        group: ansible
        mode: '0775'

    - name: Configurar permisos para directorio de configuración
      file:
        path: /etc/ansible
        owner: root
        group: ansible
        mode: '0775'
        recurse: yes

    - name: Crear directorio para playbooks
      file:
        path: /var/www/html/ansible
        state: directory
        owner: root
        group: ansible
        mode: '0775'
        recurse: yes

    - name: Crear directorio .ansible temporal
      file:
        path: /var/www/.ansible/tmp
        state: directory

    - name: Establecer propietario para .ansible
      file:
        path: /var/www/.ansible
        owner: www-data
        group: www-data
        recurse: yes

    - name: Configurar permisos para /var/www
      file:
        path: /var/www
        mode: '0755'

    - name: Configurar permisos para directorio .ansible
      file:
        path: /var/www/.ansible
        mode: '0775'
        recurse: yes

    - name: Reiniciar servicio Apache
      service:
        name: apache2
        state: restarted